var http = require('http');
var querystring = require('querystring');

var mysql = require('mysql');//定义模块
var cilent = mysql.createConnection({
	host:'localhost',
	user:'root',
	password:'tt6145',
	database:'messageboard',
	port:3306
});
cilent.connect();
var port = 80;
var ip = '127.0.0.1';
var d = new Date();
var month = d.getMonth()+1;
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (hour < 10) {
	hour = "0" + hour;
}
if (minute < 10) {
	minute = "0" + minute;
}
if (second < 10) {
	second = "0" + second;
}
var date = d.getFullYear()+'年'+month+'月'+d.getDate()+'日 '+hour+':'+minute+':'+second;

var server = http.createServer(function (request, response) {
	response.writeHead(200, {'Content-Type': 'text/html','Server':'tjg_private'});
	response.statusMessage = "hehehe";
	//response.statusCode = 404;
	//response.setHeader('Content-Type','text/html');
	//response.setHeader('Server','tjg_private');
	var url = require('url').parse(request.url,true);
	//console.log(url)
	var fs = require('fs'); // 载入fs模块
	var tjg = '404';
	var suffix= request.url.substr(request.url.lastIndexOf(".")+1);
	//console.log(suffix)
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'js':'application/x-javascript',
		'jpg':'image/jpeg',
		'png':'image/png',
	}
	response.writeHead(200, {'Content-Type': exts[suffix]});
	if (exts[suffix]==null) {
		response.writeHead(200, {'Content-Type': 'text/plain'});
	}
	var MyPage = '万事屋——有事请留言';

	if (request.url=='/index.html') {
		try{
			cilent.query("select * from board",function(err,rows,fields){
				if (err) throw err;
				item = rows;
				var s = ''
				for(var i=0;i<item.length;i++){
					s+= '<div class="item">' 
					s+= '<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>'
					s+= '<p><span id="content">'+item[i].message+'</span>'+'<a id="del" href="/delmessage?id='+item[i].Id+'">删除</a>'+'</p>'
					s+= '</div>'
				}
				var tjg = fs.readFileSync("."+request.url,'utf8');
				tjg = tjg.replace(/%title/g,MyPage)
				tjg = tjg.replace(/%main/g,s);
				response.write(tjg);
				response.end();
			});
		}catch(e){}
	}else if (request.url=='/form.html') {
		var tjg = fs.readFileSync("."+request.url,'utf8');
		response.write(tjg);
		response.end();
	}else if (url.pathname=='/addmessage') {
		// 定义了一个post变量，用于暂存请求体的信息
	    var post = '';
	    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(chunk){    
	        post += chunk;
	    });
	    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
	  
	    request.on('end', function(){    
	        post = querystring.parse(post);
			
			cilent.query("insert into board values(null,'"+post.author+"','"+date+"','"+post.message+"')",function(err,rows,fields){
				if (err) throw err;
				response.writeHead(302,{
					Location:'/index.html'
				})
				response.write(tjg);
				response.end();
			});
	    });
	}else if (url.pathname=='/delmessage') {
		var id= url.query.id;
		
		cilent.query("delete from board where id="+id,function(err,rows,fields){
			if (err) throw err;
			response.writeHead(302,{
				Location:'/index.html'
			})
			response.write(tjg);
			response.end();
		});
	}else{
		try{
			var tjg = fs.readFileSync("."+request.url);
			response.write(tjg);
			response.end();
		}catch(e){}
	}
}).listen(80);//监听80窗口

// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,port);
function delay(delaytime){
	var sleep = date.getTime()
	while(new Date() >= sleep+delaytime){}
}